package com.heima.controller;

import com.heima.pojo.AliyunOSSProperties;
import com.heima.pojo.Result;
import com.heima.utils.AliyunOSSUtils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Slf4j
@RestController
public class UploadController {
    @Autowired
    private AliyunOSSProperties aliyunOSSProperties;
//    @Value("${aliyun.oss.endpoint}")
//    private String endpoint;
//    @Value("${aliyun.oss.bucketName}")
//    private String bucketName;
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception {
        log.info("文件上传:{}", file);
        //123.png 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成一个随机
        String name = UUID.randomUUID().toString() + substring;
        //将上传的文件存储到指定位置,要有一个具体文件
//        file.transferTo(new File("D:/测试文件/a.txt"));
        //这里用阿里云的保存代替了上面文件的保存
        String uploadUrl = AliyunOSSUtils.upload(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getBucketName(), file.getBytes(), name);
        return Result.success(uploadUrl);
    }
}
